<template>
	<yd-layout id='courseVideoDetailVip' class=''>
		<div class="header_children_100" ref='headerChildrenRef' >
			<div class="header_children_100_c">
				<div class="mengban" @click='playVideo'  v-show="playBtn"></div>
				<div class="mengbanimg" v-show="playBtn" :style="mengBanImgStyle"></div>
				<img v-show='playBtn' @click='playVideo'  src="../../assets/playBtn.png" alt="" />
				<div class="h5_player">
					<!--src=https://www.w3school.com.cn//i/movie.ogg-->
					<!--:poster="videoDetail.title_img" -->
					<!--:src="videoDetail.url" -->
					<video id="test_video"
						 width="100%" 
						 ref='videoRef' 
						 height="30%" x5-video-orientation="portraint" webkit-playsinline="true" playsinline="" 
						 x5-playsinline="" x-webkit-airplay="allow" @pause="pauseVideo"
						  @playing='playIngVideo' :src="videoDetail.url"
						preload="" class="content_video text_left" style="position: inherit;width:100%;">
					</video>
				</div>
			</div>
		</div>
		<div class="content">

			<div class="content_top">
				<div class="title c_text_ellipsis_2">{{videoDetail.title}}</div>
				<div class="vip_num">
					<div v-if="videoDetail.is_buy==1" class="vip_label" style="color: #999999;">已购买</div>
					<div v-else-if="videoDetail.price>0" class="vip_label">￥{{videoDetail.price}}</div>
					<div v-else class="vip_label">免费</div>
					<div class="vip_play">
						<img src="../../assets/play_icon.png" alt="" />
						<div>{{videoDetail.watch_count}}次播放</div>
					</div>
				</div>
			</div>

			<div class="content_video">
				<div class="video_title">播放目录</div>
				<div class="video_list_f" ref='playListRef'>
					<div class="video_list_c">
						<div ref='playListItemRef' class="video_list" v-for="item,index in videoList" @click="videoClick(item,index)">
							<!--:class="item.id == videoId?'video_active':''"-->
							<div class="video_list_top">
								<div class="video_list_top_c">
									<div class="video_list_top_bk"></div>
									<img class="video_list_img" :src="item.title_img" alt="" />
									<img class="video_list_icon" src="../../assets/playBtn.png" alt="" />
								</div>
								<div class="video_list_top_title c_text_ellipsis_1">{{item.title}}</div>
							</div>

						</div>
					</div>

				</div>
			</div>

			<div class="content_share_top">
				<div class="share_title">学习分享</div>
				<div class="share_label">收听课程后，写下你的心得与收获</div>
			</div>
			<div class="content_share">
				<div class="list_item">
					<!---->
					<yd-infinitescroll v-show='commentList.length>0' :callback="getCommetnList" ref="infinitescrollDemo">
						<StudentShareList :videoComment='videoComment' @zanClick='zanClick' :audioType='false' slot="list" :dataList='commentList'></StudentShareList>
						<!-- 数据全部加载完毕显示 -->
						<span slot="doneTip">没有更多数据了~~</span>

						<!-- 加载中提示，不指定，将显示默认加载中图标 -->
						<!--<img slot="loadingTip" src="path/img/loading.svg"/>-->
					</yd-infinitescroll>
					<div v-if='commentList.length==0' class="no_list">暂无内容</div>

				</div>
			</div>
		</div>

		<div slot='bottom' class="study_bottom_f">
			<div @click="writeShare" class="study_bottom">写写学习感悟~</div>
			<!--<input type="text" />-->
		</div>
		<div class="c_go_home c_size_30_42" @click="$router.push({name:'index',query:{str:'index'}})">去首页</div>
		<yd-popup v-model="showWrite" position="bottom" height="3.82rem">
			<div class='pop_share'>
				<div class="pop_header">
					<img @click="showWrite=false" class="pop_header_img" src="../../assets/audioDetail_8.png" alt="" />
					<div class="pop_header_btn" @click="sendShare" :style="{color:(textareaVal+'').length>0?'#DCBBC9':'#999999'}">发送</div>
				</div>
				<div class="textarea">
					<textarea @blur="closeShare" placeholder="写写学习感悟~" v-model.trim="textareaVal" ref='textareaRef' maxlength="150" name="" rows="" cols=""></textarea>
					<div class="text_num">{{(textareaVal+'').length}}/150</div>
				</div>
				<!--<yd-textarea  class="textarea"   placeholder="写写学习感悟~" maxlength="150"></yd-textarea>-->
			</div>
		</yd-popup>

		<yd-popup v-model="moneyPop" position="bottom">
			<div class='pop_money'>
				<div class="money_content">
					<div class="money_content_title">零钱充值</div>
					<ul class="money_content_list">
						<li @click="num=6" :class="num==6?'list_active':''">6</li>
						<li @click="num=30" :class="num==30?'list_active':''">30</li>
						<li @click="num=60" :class="num==60?'list_active':''">60</li>
						<li @click="num=98" :class="num==98?'list_active':''">98</li>
						<li @click="num=128" :class="num==128?'list_active':''">128</li>
						<li @click="num=188" :class="num==188?'list_active':''">188</li>
					</ul>
				</div>
				<div slot='bottom' class="money_btn">
					<div class="money_btn_btn" @click="moneyBtn">确定充值</div>
				</div>
			</div>
		</yd-popup>
	</yd-layout>
</template>

<script>
	var setTime = ''
	var pingpp = require('pingpp-js');
	import StudentShareList from '../../components/StudentShareList/StudentShareList.vue'
	import { InfiniteScroll } from 'vue-ydui/dist/lib.rem/infinitescroll';
	import { BackTop } from 'vue-ydui/dist/lib.rem/backtop';
	import { Popup } from 'vue-ydui/dist/lib.rem/popup';
	export default {
		components: {
			[StudentShareList.name]: StudentShareList,
			[InfiniteScroll.name]: InfiniteScroll,
			[BackTop.name]: BackTop,
			[Popup.name]: Popup,
		},
		data() {
			return {
				num: 6, //充值金额
				videoComment: true,
				playBtn: true,
				palyOpen: false,
				h5VideoFlg: false,
				mengBanImgStyle: {},
				mineObj: {},
				showWrite: false,
				textareaVal: '',
				commentList: [],
				videoDetail: {},
				courseDetail: {}, //用这个来判断是否需要会员
				videoList: [],
				videoId: '',
				palyTime: 0,
				indexNum: 0,
				moneyPop: false,
				authObj: {},
			}
		},
		//销毁
		beforeDestroy() {
			if(this.palyOpen && setTime) {
				clearInterval(setTime)
				setTime = ''
				this.$root.submitEvent({
					kind: 0,
					lastFlg: true,
					position: this.palyTime,
				})
			}
		},
		created() {},
		watch: {

		},
		computed: {

		},
		async mounted() {
			document.title = '播放课程'
			this.videoId = this.$route.query.id
			await this.getMine();
			this.getVideoDetail()
			this.getCommetnList()
		},
		methods: {
			async moneyBtn() {
				if(this.$root.config.openId) {

				} else {
					await this.$root.getOpenId()
				}
				this.$root.ajax({
					name: 'my/recharge',
					params: {
						type: 0,
						channel: 4,
						money: this.num,
						success_url: this.$root.config.openId
						//success_url:window.location.href,
						//success_url:`${this.$root.config.shareUrl}#/success`
					}
				}).then((d) => {
					d.data.channel = 'wx_pub'
					pingpp.createPayment(d.data, (result, err) => {
						// object 需是 Charge/Order/Recharge 的 JSON 字符串
						// 可按需使用 alert 方法弹出 log
						//console.log(JSON.stringify(object));
						if(result == "success") {
							window.location.reload();
							// 只有微信JSAPI (wx_pub)、微信小程序（wx_lite）、QQ 公众号 (qpay_pub)、支付宝小程序（alipay_lite）支付成功的结果会在这里返回，其他的支付结果都会跳转到 extra 中对应的 URL
						} else if(result == "fail") {
							console.log(err.msg)
							this.$dialog.toast({
								mes: err.msg,
								timeout: 1500
							});
							// Ping++ 对象 object 不正确或者微信JSAPI/微信小程序/QQ公众号支付失败时会在此处返回
						} else if(result == "cancel") {
							this.$dialog.toast({
								mes: '已取消支付！',
								timeout: 1500
							});
							// 微信JSAPI、微信小程序、QQ 公众号、支付宝小程序支付取消支付
						}
					});
				})

			},
			//收藏
			collect(num) {
				let name = ''
				let loadingName = ''
				if(num == 1) {
					name = 'collection/cancel'
					loadingName = '请稍后...'
				} else {
					name = 'collection/collect'
					loadingName = '请稍后...'
				}
				this.$root.ajax({
					name: name,
					//closeAllLoading:true,
					loadingName: loadingName,
					params: {
						kind: 0,
						oid: this.videoId
					}
				}).then((d) => {
					if(num == 1) {
						this.$set(this.videoDetail, 'collected', 0)
						this.$dialog.toast({
							mes: '取消收藏',
							timeout: 500
						});
					} else {
						this.$set(this.videoDetail, 'collected', 1)
						this.$dialog.toast({
							mes: '收藏成功',
							timeout: 500
						});
					}
				})
			},
			//点赞
			zanClick(item) {
				console.log(item)
				let name = 'like/like'
				if(item.liked == 1) {
					name = 'like/unlike'
				}
				this.$root.ajax({
					name: name,
					loadingName: '请稍后...',
					params: {
						kind: 9,
						oid: item.id
					}
				}).then((d) => {
					if(item.liked == 1) {
						item.liked = 0;
						item.like_count--

					} else {
						item.liked = 1;
						item.like_count++
					}
					console.log(item.liked)
					this.$set(this.commentList, item.index, item)
					console.log(this.commentList[item.index])
				})
			},
			//推荐视频切换
			videoClick(item, index) {
				if(index == this.indexNum) {
					return
				}
				this.indexNum = index
				this.videoId = item.id
				if(this.palyOpen) {
					this.$root.id = this.videoId
					this.$root.submitEvent({
						kind: 0,
						lastFlg: true,
						position: this.palyTime
					})
				}
				this.playBtn = true;
				this.palyOpen = false
				if(setTime) {
					clearInterval(setTime)
					setTime = ''
					this.palyTime = 0;
				}
				this.mengBanImgStyle = {
					background: `url(${item.title_img}) no-repeat`,
					backgroundSize: `100% 100%`,
				}

				this.scrollVideo()

				this.videoDetail = Object.assign({}, this.videoDetail, item)

				this.pageNum = 1;
				this.pageCount = 10;
				this.commentList = []
				this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.reInit');
				this.getCommetnList()
			},
			scrollVideo() {
				this.$nextTick(() => {
					
					if(this.videoList.length > 2) {
						this.$nextTick(() => {
							var ListWidth = this.$refs.playListItemRef[1].offsetWidth
							console.log(this.indexNum * ListWidth)
							this.$refs.playListRef.scrollLeft = this.indexNum * ListWidth
						})
					}
				})
			},
			getVideoDetail() {
				this.$root.ajax({
					//					name: 'hqc/video',
					name: 'video/detail',
					type: 'get',
					params: {
						id: this.videoId
					}
				}).then((d) => {
					this.mengBanImgStyle = {
						background: `url(${d.data.video.title_img}) no-repeat`,
						backgroundSize: `100% 100%`,
					}
					this.courseDetail = Object.assign({}, this.courseDetail, d.data.course)

					this.$root.setMoneyZero(d.data.video, 'price')
//										 d.data.video.url = 'https://www.w3school.com.cn//i/movie.ogg'
					this.videoDetail = Object.assign({}, this.videoDetail, d.data.video)
					for(let a = 0; a < d.data.video_list.length; a++) {
						d.data.video_list[a].price = this.$root.setMoneyZero(d.data.video_list[a], 'price')
//												d.data.video_list[a].url = 'https://www.w3school.com.cn//i/movie.ogg'
						if(d.data.video_list[a].id == this.videoId) {
							this.indexNum = a
						}
					}
					this.videoList = d.data.video_list;

					//权限判断
					this.authFlg();
					//this.scrollVideo()
					//分享
					if(this.$root.isWeiXin()) {
						//分享
						let query = '';
						if(this.$root.config.channel) {
							query = `params=channelDY2FGoldUrlStrDY${this.$route.name}FGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.videoId}`
						} else {
							query = `params=oldUrlStrDY${this.$route.name}FGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.videoId}`
						}
						this.$root.wxShare({
							d: this.videoDetail, //分享对象，题目等{title:'',title-img:''}
							query: query, //参数
							desc: `${this.videoDetail.watch_count}次播放` //分享详情
						})
					}

				})
			},
			closeShare() {
				setTimeout(function() {
					var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
					window.scrollTo(0, Math.max(scrollHeight - 0.01, 0));
				}, 150);
				setTimeout(() => {
					this.showWrite = false
				}, 250)

			},
			getCommetnList(flg) {
				this.$root.ajax({
					name: 'comment/lst',
					type: 'get',
					closeAllLoading: flg ? true : false,
					params: {
						page: this.pageNum,
						count: this.pageCount,
						kind: 100,
						oid: this.videoId
					}
				}).then((d) => {
					let date = new Date()
					for(let a = 0; a < d.data.comment_list.length; a++) {
						//刚刚
						if(date - d.data.comment_list[a].create_time * 1000 < 60 * 1000) { //60s
							d.data.comment_list[a].newTime = '刚刚'
						} else if(date - d.data.comment_list[a].create_time * 1000 < 5 * 60 * 1000) { //5min
							d.data.comment_list[a].newTime = '5分钟之内'
						} else if(date - d.data.comment_list[a].create_time * 1000 < 30 * 60 * 1000) { //30min
							d.data.comment_list[a].newTime = '30分钟之内'
						} else if(date - d.data.comment_list[a].create_time * 1000 < 3 * 60 * 60 * 1000) { //3h
							d.data.comment_list[a].newTime = '3小时之内'
						} else if(date - d.data.comment_list[a].create_time * 1000 < 24 * 60 * 60 * 1000) { //24
							d.data.comment_list[a].newTime = '24小时之内'
						} else {
							let plDate = new Date(d.data.comment_list[a].create_time * 1000)
							let month = plDate.getMonth()
							let day = plDate.getDate()
							if(date.getFullYear() == plDate.getFullYear()) {
								d.data.comment_list[a].newTime = (month + 1 < 10 ? '0' + (month + 1) : (month + 1)) + '-' + (day < 10 ? '0' + day : day)
							} else {
								d.data.comment_list[a].newTime = plDate.getFullYear() + '-' + (month + 1 < 10 ? '0' + (month + 1) : (month + 1)) + '-' + (day < 10 ? '0' + day : day)
							}
						}
					}

					console.log(d.data)
					this.commentList = [...this.commentList, ...d.data.comment_list];
					if(this.commentList.length >= d.data.comment_total) {
						/* 所有数据加载完毕 */
						this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
						return;
					}

					/* 单次请求数据完毕 */
					this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');

					this.pageNum++;
				})
			},
			writeShare() {
				//				this.$router.push({name:'audioStudentShare',query:{oid:this.videoId}})
				this.showWrite = true
				this.$refs.textareaRef.focus();
			},
			authFlg() {
				this.$root.courseAuthFlg({
					id: this.videoDetail.course_id,
					msg: true,
					isBuyCouse: this.videoDetail.is_buy == 1 ? true : false,
				}).then((data) => {
					this.authObj = Object.assign({}, this.authObj, data)
				})
			},
			playVideo() {
				this.$nextTick(() => {
					if(this.authObj.code == 0) {
						if(this.videoDetail.is_buy == 1 || this.videoDetail.price == 0) {
							this.videoPlayFunc();
						} else {
							this.$dialog.confirm({
								title: '温馨提示',
								mes: `这节课需要付费观看哦~`,
								opts: [{
										txt: '知道了',
										stay: false,
										color: '#999999',
										callback: () => {

										}
									},
									{
										txt: '立即购买',
										color: '#DCBBC9',
										callback: () => {
											this.buyCourse(this.videoDetail.id)
										}
									},
								]
							});
						}
					} else {
						this.$dialog.confirm({
		                    title: '温馨提示',
		                    mes: `<span style='color:#A1A1A1;'>${this.authObj.msg}</span>`,
		                    opts: [
		                        {
		                            txt: '知道了',
		                            stay: false,
		                            color: '#DCBBC9',
		                            callback: () => {
		                            	
				                    }
		                        },
		                    ]
		                });
					}

				})

			},
			//购买课程
			buyCourse(id) {
				return new Promise((resolve, reject) => {
					this.$root.ajax({
						name: 'video/buy',
						errormsg: true,
						closeDia: true,
						params: {
							id: id //	课程ID
						}
					}).then((d) => {
						if(d.code == 0) {
							this.videoDetail.is_buy = 1
							this.$set(this.videoDetail, 'is_buy', 1)
							this.$set(this.videoList, this.indexNum, this.videoDetail)
						} else if(d.code == 1002) {
							//余额不足
							this.moneyPop = true;

						} else {
							this.$dialog.toast({
								mes: d.msg,
								timeout: 1500
							});
						}

					})
				})
			},
			videoPlayFunc() {
				this.playBtn = false
				this.palyOpen = true
				this.h5VideoFlg = true
				var myVideo = this.$refs.videoRef;
				myVideo.play();
				
				this.$root.id = this.videoId
				this.$root.uuid = (parseInt((parseInt(new Date() - 0)) / 1000)) + '' + (this.$root.userInfo.me.id || 0)
				this.$root.submitEvent({
					kind: 0,
					position: myVideo.currentTime,
				})

			},
			pauseVideo() {
				//this.palyOpen = false
				var myVideo = this.$refs.videoRef;
				this.$root.id = this.videoId
				myVideo.pause();
//				if(setTime) {
//					clearInterval(setTime);
//					this.palyTime = 0;
//					setTime = ''
//				}
				if(myVideo&&false) {
					this.$root.submitEvent({
						kind: 0,
						lastFlg: true,
						position: myVideo.currentTime
					})
				}
			},
			playIngVideo() {
				var myVideo = this.$refs.videoRef;
				myVideo.setAttribute('controls', 'controls')
				this.palyOpen = true
				this.palyTime = myVideo.currentTime;

				setTime = setInterval(() => {
					this.palyTime++
				}, 1000)

				
			},
			getMine() {
				return new Promise((resolve, reject) => {
					this.$root.ajax({
						name: 'my',
						params: {}
					}).then((d) => {
						this.mineObj = Object.assign({}, this.mineObj, d.data)
						resolve()
					})
				})

			},
			sendShare() {
				if(this.textareaVal) {
					this.$root.ajax({
						name: 'comment/doComment',
						params: {
							kind: 100,
							oid: this.videoId,
							content: this.textareaVal,
						}
					}).then((d) => {
						this.showWrite = false;
						this.textareaVal = ''
						this.pageNum = 1;
						this.pageCount = 10;
						this.commentList = []
						this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.reInit');
						this.getCommetnList(true)
						this.$dialog.toast({
							mes: '评论成功',
							timeout: 1500,
							icon: 'success',
							callback: () => {

							}
						});
					})
				} else {
					this.$dialog.toast({
						mes: '请输入学习感悟~',
						timeout: 1500,
					});
				}
			},
		}
	}
</script>

<style lang="scss">
	@import './courseVideoDetailVip.scss';
</style>